import os
from applications.configs.common import VIDEO_PATH


def get_video_list():
    # 获取文件
    video_list = []
    for video in os.listdir(VIDEO_PATH):
        video_res = {"name": video, "content": []}
        # 获取文件路径
        video_path = os.path.join(VIDEO_PATH, video)
        # 判断是否是文件夹
        if os.path.isdir(video_path):
            # 获取文件夹下的文件
            for i in os.listdir(video_path):
                video_res["content"].append({"name": i, "path": "/videos/{}/{}".format(video, i)})
        video_list.append(video_res)
    return video_list


# 读取视频流
def stream_video(video_path: str, start: int, end: int):
    with open(video_path, "rb") as video_file:
        video_file.seek(start)
        remaining_bytes = end - start + 1
        while remaining_bytes > 0:
            chunk_size = min(remaining_bytes, 1024 * 1024)  # 每次读取 1MB 数据
            data = video_file.read(chunk_size)
            if not data:
                break
            remaining_bytes -= len(data)
            yield data


# 分段传输
def segmented_transfer(video, name, request):
    video_path = "{}/{}/{}".format(VIDEO_PATH, video, name)
    if not os.path.exists(video_path):
        return False, "没有该地址"

    file_size = os.path.getsize(video_path)
    range_header = request.headers.get("range")
    if range_header:
        range = range_header.strip().replace("bytes=", "").split("-")
        start = int(range[0])
        end = min(int(range[1]), file_size - 1) if range[1] else file_size - 1
        content_length = end - start + 1
        headers = {
            "Content-Range": f"bytes {start}-{end}/{file_size}",
            "Accept-Ranges": "bytes",
            "Content-Length": str(content_length),
            "Content-Type": "video/mp4",
        }
        return stream_video(video_path, start, end), headers
    else:
        return False, "暂不接受全部传输"